﻿using System.Threading.Tasks;
using AbpOne.Application.Contracts.Blog;
using AbpOne.Domain.Blog;
using AbpOne.Domain.Blog.Repositories;
using AbpOne.ToolKits.Base;

namespace AbpOne.Application.Blog.Impl {
    public class BlogService : ServiceBase, IBlogService {
        private readonly IPostRepository _postRepository;

        public BlogService(IPostRepository postRepository) {
            _postRepository = postRepository;
        }

        public async Task<ServiceResult<string>> InsertPostAsync(PostDto dto) {
            var result = new ServiceResult<string>();

            // var entity = new Post {
            //     Title = dto.Title,
            //     Author = dto.Author,
            //     Url = dto.Url,
            //     Html = dto.Html,
            //     Markdown = dto.Markdown,
            //     CategoryId = dto.CategoryId,
            //     CreationTime = dto.CreationTime
            // };

            // 使用AutoMapper
            var entity = ObjectMapper.Map<PostDto, Post>(dto);

            var post = await _postRepository.InsertAsync(entity);

            if (post == null) {
                return result.Fail("添加失败");
            }

            return result.Success("添加成功");
        }


        public async Task<ServiceResult> DeletePostAsync(int id) {
            var result = new ServiceResult();

            await _postRepository.DeleteAsync(id);

            return result.Success("删除成功");
        }

        public async Task<ServiceResult<string>> UpdatePostAsync(int id, PostDto dto) {
            var result = new ServiceResult<string>();

            var post = await _postRepository.GetAsync(id);
            if (post == null) {
                return result.Fail("文章不存在！");
            }

            post.Title = dto.Title;
            post.Author = dto.Author;
            post.Url = dto.Url;
            post.Html = dto.Html;
            post.Markdown = dto.Markdown;
            post.CategoryId = dto.CategoryId;
            post.CreationTime = dto.CreationTime;

            await _postRepository.UpdateAsync(post);

            return result.Success("更新成功");
        }

        public async Task<ServiceResult<PostDto>> GetPostAsync(int id) {
            var result = new ServiceResult<PostDto>();

            var post = await _postRepository.GetAsync(id);

            if (post == null) {
                return result.Fail("文章不存在");
            }

            // var dto = new PostDto {
            //     Title = post.Title,
            //     Author = post.Author,
            //     Url = post.Url,
            //     Html = post.Html,
            //     Markdown = post.Markdown,
            //     CategoryId = post.CategoryId,
            //     CreationTime = post.CreationTime
            // };
            
            // 使用AutoMapper映射，省去手动赋值
            var dto = ObjectMapper.Map<Post, PostDto>(post);

            return result.Success(dto, message: "获取文章成功");
        }
    }
}